<?php

/**
 * Hello World Controller
 */
class AccountController extends ControllerBase
{
	/**
	 * Initialisiert den Controller
	 */
	public function Init()
	{ }

	/**
	 * Index Methode wird aufgerufen wenn Index
	 * oder keine Action angefordert wurde.
	 */
	public function Index()
	{
		if ($this->page->IsLoggedIn())
		{
		}
		else
		{
			return $this->ShowLogin();
		}
	}
	
	public function ShowLogin()
	{
		$res = new ViewResponse();
		
		$this->User = "";
		if (!empty($_REQUEST["u_name"]))
			$this->User = $_REQUEST["u_name"];
		
		$res->view = $this->View("account_login_screen");
		
		return $res;
	}
	
	public function Login()
	{
		$res = new ViewResponse();
		
		if (empty($_REQUEST["u_name"]))
			$res->error = "Kein Benutzername angegeben";
		else if (empty($_REQUEST["u_pass"]))
			$res->error = "Kein Passwort angegeben";
		
		
		if (empty($res->error))
		{
			$dao = new DAO_Account();
			
			$token = $dao->PerformLogin($_REQUEST["u_name"], $_REQUEST["u_pass"]);
			if (!empty($token))
			{
				$_SESSION["alDente-auth"] = $token;
				$this->RedirectTo("Home");
			}
			else
			{
				$res->error = "Fehler beim Anmelden";
			}
		}
		
		$res->view = $this->ShowLogin()->view;
		
		return $res;
	}
	
	public function Logout()
	{
		$_SESSION["alDente-auth"] = "";
		$this->RedirectTo("Home");
	}

	public function IsLogedIn()
	{
		if (isset($_SESSION["alDente-auth"]) && !empty($_SESSION["alDente-auth"]))
		{
			$isGueltig = Security::checkToken($_SESSION["alDente-auth"]);
			if (!$isGueltig)
				$_SESSION["alDente-auth"] = "";
				
			return $isGueltig;
		}
		
		return false;
	}
	
	public function GetUserName()
	{
		if (isset($_SESSION["alDente-auth"]) && !empty($_SESSION["alDente-auth"]))
		{
			$dao = new DAO_Account();
			return $dao->GetUserName($_SESSION["alDente-auth"]);
		}
		
		return "";
	}
}

?>